import {
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { ChatsService } from './chats.service';
import { Server, Socket } from 'socket.io';
import { MessageService } from 'src/message/message.service';

interface IJoinRoomPayload {
  roomId: string;
  userId: number;
}

interface ISendMessagePayload {
  userId: number;
  roomId: string;
  message: {
    type: number;
    content: string;
  };
}

@WebSocketGateway({ cors: { origin: '*' } })
@WebSocketGateway()
export class ChatsGateway {
  @WebSocketServer() server: Server;
  constructor(
    private readonly chatsService: ChatsService,
    private readonly messageServie: MessageService,
  ) {}

  @SubscribeMessage('joinRoom')
  joinRoom(client: Socket, payload: IJoinRoomPayload) {
    const roomName = payload.roomId + '';

    client.join(roomName);

    this.server.to(roomName).emit('message', {
      type: 'joinRoom',
      userId: payload.userId,
    });
  }

  @SubscribeMessage('sendMessage')
  async sendMessage(@MessageBody() payload: ISendMessagePayload) {
    const roomName = payload.roomId + '';

    await this.messageServie.create({
      userId: payload.userId,
      roomId: payload.roomId,
      content: payload.message.content,
      type: payload.message.type,
    });

    this.server.to(roomName).emit('message', {
      type: 'sendMessage',
      userId: payload.userId,
      message: payload.message,
    });
  }
}
